package com.java.service;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.*;

import com.java.db.CommonConnect;

/**
 * Dao를 접근하기 위한 service
 * @author 
 * @version 1.0
 */
public class CommonDaoService
{
	private Class classname = null;
	private Method[] method = null;
	private ArrayList list = null;
	private Method returnMethod = null;
	private Object obj = null;
	private Connection con = null;
	
	public CommonDaoService(String className){
		try {
			System.out.println("className ===========> " + className);
			className = "com.java.dao." + className; //DAO의 경로를 가지고 온다
			this.classname = Class.forName(className); //리플렉션 이용
			obj = classname.newInstance();
			method = classname.getMethods();
			
			con = (new CommonConnect()).getConnection_ds1();
			
			for(int i=0; i<method.length; i++){
				if(method[i].getName().equals("execute")){ //CommonDao에서 상속받은 execute메소드를 반드시 사용
					this.returnMethod = classname.getMethod(method[i].getName(), new Class[]{HashMap.class,Connection.class});
				}
			}
		} catch (Exception e) {
			if(e.toString().contains("ClassNotFoundException")){
				System.out.println("error ==================> 클래스 이름을 확인하세요");
			}
			e.printStackTrace();
		} finally {
			try{
				//if (con!=null) con.setAutoCommit(true);
				//if (con!=null) con.close();
			}catch(Exception ee){}
		}
	}
	
   public ArrayList commonDaoMethod(Map requestMap ) throws Exception
    {
        //return (ArrayList)classname.getMethod("execute", requestMap.getClass()).getDefaultValue();
	   
	   ArrayList list = new ArrayList();
	   try {
	   //requestMap의 값을 찍어보기위한 로그 Start
	   System.out.println("===========================");
	   Set set = requestMap.keySet(); 
	   Iterator it = set.iterator();
	   String key ="";
	   while(it.hasNext()){
		   key = (String)it.next();
		   System.out.println("key ==> " + key + " : value ==> " + requestMap.get(key));
	   }
	   System.out.println("===========================");
	   //requestMap의 값을 찍어보기위한 로그 End
	   
	   list = (ArrayList)returnMethod.invoke(obj, new Object[]{new HashMap(requestMap), con});  //리플렉션을 이용해서 메소드 실행
	   
	   }catch(Exception e) {
		  e.printStackTrace(); 
	   }finally {
			try{
				if (con!=null) con.setAutoCommit(true);
				if (con!=null) con.close();
			}catch(Exception ee){}
		}
	   
	   return list;
    }
    
}
